package middleware

import (
	"context"
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/utils"

	"github.com/gin-gonic/gin"
)

// JwtUserAuth 用户验证中间件
func JwtUserAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("token")
		if token == "" {
			c.Abort()
			http.FailWithMessage("会话结束，请重写登录", c)
			return
		}
		claims, err := utils.ParseToken(token)
		if err != nil {
			c.Abort()
			common.Log.Error(err.Error())
			http.FailWithMessage("会话结束，请重写登录", c)
			return
		}
		// 判断token是否在redis当中
		//redisClient := core.InitRedis()
		//value, _ := redisClient.Get("logout_" + token)

		value := common.Redis.Get(context.Background(), "logout_"+token).Val()
		if value == token {
			c.Abort()
			http.FailWithMessage("会话结束，请重写登录", c)
			return
		}
		c.Set("user", claims)
		c.Next()
	}
}
